package com.offcn.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 封装对表进行操作的servlet类，便于操作表
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决post请求中文乱码问题
        request.setCharacterEncoding("UTF-8");
        //解决post方法响应乱码问题
        response.setContentType("text/html;charset=utf-8");
        //获取处理业务逻辑的方法名
        String method = request.getParameter("method");
        //获取当前servlet的字节码对象
        Class clazz = this.getClass();
        //未传递method方法名时，默认给一个demo的方法名
        if(method==null||method.trim().length() ==0){
            method = "demo";
        }
        try {
            //通过字节码对象获取和方法名以及参数相应的方法对象
            Method m = clazz.getMethod(method,HttpServletRequest.class,HttpServletResponse.class);
            //执行当前servlet对应的方法，获得返回值（转发路径）
            String path = (String) m.invoke(this,request,response);
            //当获取到返回的转发路径时，进行转发，转发一次响应，一次请求
            if(path!=null){
                request.getRequestDispatcher(path).forward(request,response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
